package my.syncfilter;


import my.syncfilter.entity.FileEntity;
import my.syncfilter.entity.SumFile;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class BackUpFileProcessor extends AbstractFileProcessor {
    private static Logger logger = LoggerFactory.getLogger(BackUpFileProcessor.class);

    public BackUpFileProcessor(String prefix) {
        super(prefix);
    }

    @Override
    public boolean process(FileEntity data) {
        //复制文件
        if (!StringUtils.isEmpty(billConfig.getFileBackupBasePath())) {
            //有压缩文件备份压缩文件
            SumFile zip = data.getZip();
            if (zip == null) {
                //没有压缩文件备份明细文件
                zip = data.getSumFile();
            }
            if (zip != null && zip.getFileName() != null) {
                try {
                    boolean exists = Files.exists(Paths.get(billConfig.getFileBackupBasePath()));
                    if (!exists) {
                        Files.createDirectories(Paths.get(billConfig.getFileBackupBasePath()));
                    }
                    copy(zip);
                } catch (Exception e) {
                    logger.error("复制文件异常", e);
                }
            }
        }

        //删除文件
        if ("1".equals(billConfig.getUploadDel())) {
            SumFile sumFile = data.getSumFile();
            try {
                //没有备份只删除 txt 明细文件
                if(StringUtils.isEmpty(billConfig.getFileBackupBasePath())){
                    if (sumFile != null && sumFile.getFileName() != null) {
                        Files.delete(Paths.get(sumFile.getBasePath(), sumFile.getFileName()));
                    }
                }else{
                    if (sumFile != null && sumFile.getFileName() != null) {
                        Files.delete(Paths.get(sumFile.getBasePath(), sumFile.getFileName()));
                    }
                    SumFile zip = data.getZip();
                    if (zip != null && zip.getFileName() != null)
                        Files.delete(Paths.get(zip.getBasePath(), zip.getFileName()));
                }
            } catch (Exception e) {
                logger.error("删除文件异常", e);
            }
        }
        return false;
    }

    public void copy(SumFile zip) throws Exception {
        try {
            Files.copy(Paths.get(zip.getBasePath(), zip.getFileName()), Paths.get(billConfig.getFileBackupBasePath(), zip.getFileName()));
        } catch (FileAlreadyExistsException e) {
            copy(zip);
        }
    }
}